package com.itheima.Demo;

import com.itheima.bean.Student;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/*
 * 飞机
 * 工厂
 * 工人
 * 图纸
 * */
public class Demo01 {
    private SqlSession sql;

    //1.加载核心配置文件
    @Before
    public void init() {
        InputStream is = Student.class.getClassLoader().getResourceAsStream("MyBatisConfig.xml");

        //2.获取SqlSession工厂对象
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(is);
        //3.通过SqlSession工厂对象获取SqlSession对象
        sql = build.openSession();
    }

    @After
    public void destroy() {
        sql.commit();
        sql.close();

    }


    //4.执行映射配置文件中的sql语句，并接收结果
    @Test
    public void findAll() {
        List<Student> list = sql.selectList("StudentMapper.findAll");
        //5.处理结果
        for (Student stu : list) {
            System.out.println(stu);
        }
    }

    @Test
    public void findById() {
        Student student = sql. selectOne("StudentMapper.findById", 1);
        //5.处理结果
        System.out.println(student);
    }

    @Test
    public void save() {
        Student stu = new Student(10, "章若楠", 18);
        Integer insert = sql.insert("StudentMapper.save",stu);
        System.out.println(insert);
    }
    @Test
    public void update(){
        Student stu = new Student(2,"张无忌",25);
        int update = sql.update("StudentMapper.update", stu);
        System.out.println(update);

    }
    @Test
    public void  delete(){
        int delete = sql.delete("StudentMapper.delete", 1);
        System.out.println(delete);

    }


}
